//
//  FQDPieChart.m
//  FakeQDaily
//
//  Created by mewxiv on 9/18/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDPieChart.h"

@implementation FQDPieChartSlice


+ (instancetype)sliceWithPercent:(CGFloat)percent color:(UIColor *)color
{
    FQDPieChartSlice *slice = [[self class] new];
    slice.percent = percent;
    slice.color = color;
    return slice;
}

@end

@implementation FQDPieChart

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _fillColor = [UIColor whiteColor];
        self.slices = [NSMutableArray array];
        self.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    CGFloat radius = MIN(rect.size.width, rect.size.height) / 2;
    
    CGContextSetLineWidth(context, 1.0f);
    CGContextSetFillColorWithColor(context, self.fillColor.CGColor);
    CGContextAddArc(context, center.x, center.y, radius, 0, 2 * M_PI, YES);
    CGContextDrawPath(context, kCGPathFill);
    
    
    CGFloat startAngle = -M_PI / 2;
    for (FQDPieChartSlice *slice in self.slices) {
        CGFloat percent = slice.percent;
        UIColor *color = slice.color;
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGFloat endAngle = startAngle + MIN(MAX(percent, 0), 1) * 2 * M_PI;
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, NO);
        CGContextFillPath(context);
        startAngle = endAngle;
    }

}

- (void)setFillColor:(UIColor *)fillColor
{
    _fillColor = fillColor;
    
    [self setNeedsDisplay];
}

- (void)setSlices:(NSArray<FQDPieChartSlice *> *)slices
{
    _slices = slices;
    
    [self setNeedsDisplay];
}

@end
